package com.bright.ghj.overt.cas;

import com.bright.ghj.user.cas.AbstractCasUserDetailsService;
import com.bright.ghj.user.security.SecurityAuthority;
import com.bright.ghj.common.util.StringUtil;
import com.bright.ghj.overt.constant.SystemConstant;
import com.bright.ghj.overt.manager.UserManager;
import com.bright.ghj.overt.pojo.dto.RightRoleDTO;
import com.bright.ghj.overt.pojo.dto.UserDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author txf
 * @Date 2022/6/24 15:52
 * @Description
 */
@Component
@RequiredArgsConstructor
public class CasUserDetailsServiceImpl extends AbstractCasUserDetailsService<UserDTO> {

    private final UserManager userManager;

    @Override
    protected UserDTO getUserByToken(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
        String loginName = token.getName();
        UserDTO user = userManager.getUserByUserName(loginName);
        user.setUserName(user.getUsername());
        user.setAllDistName(user.getDistName());
        user.setRoleName(user.getCwgkPmainDesc());
        return user;
    }

    @Override
    protected Set<SecurityAuthority> getAuthorities(UserDTO user) {
        Set<SecurityAuthority> authorities = new HashSet<>();
        // 根据导航权限 添加关键词
        for (RightRoleDTO rightRole : user.getRightRoles()) {
            if (StringUtil.isEmpty(rightRole.getNavigateKeyword())) {
                continue;
            }
            SecurityAuthority securityAuthority = new SecurityAuthority();
            String authority =  rightRole.getNavigateKeyword();
            securityAuthority.setAuthority(authority);
            authorities.add(securityAuthority);
        }
        // 获取是否有进入后台管理的权限
        if (user.getIsPermitAdmin()) {
            SecurityAuthority securityAuthority = new SecurityAuthority();
            securityAuthority.setAuthority(SystemConstant.IS_PERMIT_ADMIN);
            authorities.add(securityAuthority);
        }
//        System.out.println(authorities);
        return authorities;
    }
}
